package com.sdk.springbootdynamicschedule.dynamicone;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

@Component
@Data
public class DynamicScheduler implements SchedulingConfigurer {
    @Value("${dynamic.cron}") // 从配置读取cron
    private String cronExpression;

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        registrar.addTriggerTask(
                () -> System.out.println("动态任务执行"),
                triggerContext -> new CronTrigger(cronExpression)
                        .nextExecutionTime(triggerContext).toInstant()
        );
    }
}
